//
//  SWGeneralSettingViewController.swift
//  ChildStory
//
//  Created by linhan on 16/7/16.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWGeneralSettingViewController: SWBaseViewController,UITableViewDataSource,UITableViewDelegate,SWAPIComponent
{
    private var _settings:[[SettingItem]] = []
    
    private var _tableView:UITableView!
    
    private enum SettingAction:Int
    {
        case Account
        case About
        case RecordDocument
        case RecordDocumentPage
        case Feedback
        case NightMode
        case ClearCache
    }
    
    private class SettingItem
    {
        var title:String
        var sub:Bool
        var action:SettingAction
        var rowHeight:CGFloat
        var icon:UIImage?
        
        init(title:String, sub:Bool, action:SettingAction, rowHeight:CGFloat)
        {
            self.title = title
            self.sub = sub
            self.action = action
            self.rowHeight = rowHeight
        }
    }
    
    lazy private var _uploadSwitch:UISwitch = UISwitch()
    lazy private var _playableSwitch:UISwitch = UISwitch()
    
    lazy private var _capacityLabel:UILabel = UILabel()
    
    deinit
    {
        //NSNotificationCenter.defaultCenter().removeObserver(self)
        trace("DEINIT SWGeneralSettingViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        title = "设置"
        
        let RowHeight:CGFloat = 0
        let clearCacheItem = SettingItem(title: "清除缓存", sub: false, action:.ClearCache, rowHeight:RowHeight)
        let recordDocumentItem = SettingItem(title: "下载音乐播放", sub: false, action:.RecordDocument, rowHeight:RowHeight)
        let recordDocumentPageItem = SettingItem(title: "仅WIFI下同步照片", sub: false, action:.RecordDocumentPage, rowHeight:RowHeight)
        let aboutItem = SettingItem(title: "关于我们", sub: true, action:.About, rowHeight:RowHeight)
        
        let section1:[SettingItem] = [clearCacheItem, recordDocumentItem, recordDocumentPageItem]
        let section2:[SettingItem] = [aboutItem]
        
        _settings.append(section1)
        _settings.append(section2)
        
        //是否记录文档浏览历史
        _uploadSwitch.sizeToFit()
        _uploadSwitch.isOn = SW.Config.autoUploadOnWifi
        _uploadSwitch.addTarget(self, action: #selector(watermarkSwitchValueChanged(_:)), for: .valueChanged)
        
        //是否记录文档上次浏览页面
        _playableSwitch.sizeToFit()
        _playableSwitch.isOn = SW.Config.musicPlayableOnCellular
        _playableSwitch.addTarget(self, action: #selector(recordDocumentPageSwitchValueChanged(_:)), for: .valueChanged)
        
        _capacityLabel.textColor = UIColor(hex:0x93948f)
        _capacityLabel.textAlignment = .right
        _capacityLabel.frame = CGRectMake(0, 0, 100, 20)
        
        _tableView = UITableView(frame: view.bounds, style: UITableViewStyle.grouped)
        _tableView.dataSource = self
        _tableView.delegate = self
        _tableView.backgroundColor = UIColor(hex:0xf5f5f5)
        _tableView.rowHeight = 55
        _tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15)
        view.addSubview(_tableView)
        if #available(iOS 8.0, *) {
            _tableView.layoutMargins = _tableView.separatorInset
        }
        
        let footerView:UIView = UIView()
        footerView.frame = CGRectMake(0, 0, view.width, 90)
        _tableView.tableFooterView = footerView
        
        let logoutBtnHeight:CGFloat = 50
        let logoutBtnWidth:CGFloat = view.width * 0.564
        let logoutBtnX:CGFloat = (view.width - logoutBtnWidth) * 0.5
        let logoutBtn:UIButton = UIButton(type:.system)
        logoutBtn.setTitleColor(UIColor.white, for: .normal)
        logoutBtn.titleLabel?.font = UIFont.systemFont(ofSize:18)
        logoutBtn.setTitle("退出", for: .normal)
        logoutBtn.layer.cornerRadius = 4
        logoutBtn.layer.masksToBounds = true
        logoutBtn.backgroundColor = UIColor(hex: 0xf46263)
        logoutBtn.addTarget(self, action: #selector(logoutBtnTapped), for: .touchUpInside)
        logoutBtn.frame = CGRectMake(logoutBtnX, footerView.height - logoutBtnHeight, logoutBtnWidth, logoutBtnHeight)
        footerView.addSubview(logoutBtn)
    }
    
    //更新缓存大小
    private func updateCacheCapacity()
    {
        let paths:[String] = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
        if let cachePath = paths.valueAt(0)
        {
            DispatchQueue.global(priority: .default).async {
                let size:String = FileUtility.memoryFormatter(Double(FileUtility.folderSizeAtPath(cachePath)))
                DispatchQueue.main.async {
                    self._capacityLabel.text = size
                }
            }
        }
    }
    
    //清除缓存
    private func clearCache()
    {
        _capacityLabel.text = FileUtility.memoryFormatter(0)
    }
    
    private func askForLogout()
    {
        ActionSheet.show("您确定要退出当前登录用户吗？", buttons: ["退出","取消"], closeHandler: {buttonIndex in
            
            if buttonIndex == 0
            {
                self.logout()
            }
        }, destructiveButtonIndex: 0, cancelButtonIndex: 1)
    }
    
    private func logout()
    {
        load(SWLogoutReq())
        SWAccountManager.sharedManager().logout()
        NotificationCenter.default.post(name: NotificationName.Logout, object: nil, userInfo: nil)
    }
    
    //MARK ================================= UITableViewDelegate =========================
    
    //返回每个section的高度，默认为0，为0时不显示section
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
    {
        return 7
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat
    {
        return 7
    }
    
    //返回section的个数
    func numberOfSections(in tableView:UITableView)->Int
    {
        return _settings.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return _settings[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        var cell:UITableViewCell?
        if let item = _settings.valueAt(indexPath.section)?.valueAt(indexPath.row)
        {
            let action = item.action
            let identifier:String = action == SettingAction.Account ? "FormImageCell" : "Cell"
            cell = tableView.dequeueReusableCell(withIdentifier: identifier)
            if cell == nil
            {
                cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
            }
            
            
            if item.action == .ClearCache
            {
                updateCacheCapacity()
                cell?.accessoryView = _capacityLabel
            }
            else if item.action == .RecordDocument
            {
                cell?.accessoryView = _uploadSwitch
            }
            else if item.action == .RecordDocumentPage
            {
                cell?.accessoryView = _playableSwitch
            }
            else
            {
                cell?.accessoryView = nil
            }
            
            if #available(iOS 8.0, *) {
                cell?.layoutMargins = UIEdgeInsetsMake(0, 15, 0, 15)
            }
            else{
                cell?.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15)
            }
            
            cell?.accessoryType = item.sub ? .disclosureIndicator : .none
            cell?.textLabel?.textColor = UIColor(hex:0x4b4b4b)
            cell?.textLabel?.font = UIFont.systemFont(ofSize: 15)
            cell?.textLabel?.text = item.title
            cell?.imageView?.image = item.icon
        }
        return cell ?? UITableViewCell()
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at: indexPath, animated: true)
        if let item = _settings.valueAt(indexPath.section)?.valueAt(indexPath.row)
        {
            if item.action == .ClearCache
            {
                clearCache()
            }
            else if item.action == .About
            {
                //navigationController?.pushViewController(SWAboutUsViewController(), animated: true)
                //SWViewControllerMediator.push(SWViewController.AboutUS, param: nil, animated:true, from: navigationController)
            }
        }
    }
    
    //水印开关
    @objc private func watermarkSwitchValueChanged(_ permissionSwitch:UISwitch)
    {
        SW.Config.autoUploadOnWifi = permissionSwitch.isOn
    }
    
    @objc private func recordDocumentPageSwitchValueChanged(_ permissionSwitch:UISwitch)
    {
        SW.Config.musicPlayableOnCellular = permissionSwitch.isOn
    }
    
    @objc private func logoutBtnTapped()
    {
        askForLogout()
    }
    
    
}
